package com.demo.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channelGroup.writeAndFlush("[系统][" + formatter.format(LocalDateTime.now()) + "]" + ctx.channel().remoteAddress() + "进入房间~");
        channelGroup.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        channelGroup.writeAndFlush("[系统][" + formatter.format(LocalDateTime.now()) + "]"
                + ctx.channel().remoteAddress() + "离开房间~");
        channelGroup.remove(ctx.channel());
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String format = String.format("%s进入房间.....", ctx.channel().remoteAddress());
        System.out.println(format);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String format = String.format("%s离开房间.....", ctx.channel().remoteAddress());
        System.out.println(format);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            String mg;
            if (ch == channel) {
                mg = String.format("[自己][%s][%s]:%s",
                        channel.remoteAddress(),
                        formatter.format(LocalDateTime.now()),
                        msg);
            } else {
                mg = String.format("[访客][%s][%s]:%s",
                        channel.remoteAddress(),
                        formatter.format(LocalDateTime.now()),
                        msg);
            }
            ch.writeAndFlush(mg);
        });
    }
}
